package org.xshaokuang.loginandemail.email;

import cn.nukkit.Player;
import cn.nukkit.form.element.ElementButton;
import cn.nukkit.form.handler.FormResponseHandler;
import cn.nukkit.form.window.FormWindowSimple;
import cn.nukkit.item.Item;
import org.xshaokuang.loginandemail.MainPlugin;
import org.xshaokuang.loginandemail.tool.Tool;

import java.util.List;

public class EmailForm {
    private static EmailDataManager manager = MainPlugin.getInstance().getEmailDataManager();

    // 主界面表单
    public static void showMainForm(Player player, List<EmailData> emails) {
        if(emails == null || emails.isEmpty()) {
            player.sendMessage("§c当前没有邮件");
            return;
        }
        FormWindowSimple form = new FormWindowSimple("邮件列表", "当前共有 " + emails.size() + " 封邮件");

        for (EmailData email : emails) {
            String buttonText = String.format(
                    "来自%s §l§e%s\n§r§7有效期: %d天 §a%s",
                    email.getFrom(),
                    formatTime(email.getTimestamp()),
                    email.getKeepDays(),
                    getStatusText(email.getFlag())
            );

            form.addButton(new ElementButton(buttonText));;
        }
        form.addHandler(FormResponseHandler.withoutPlayer(ignored -> {
            if (form.wasClosed()) return;
            // 获取点击的按钮索引
            int buttonId = form.getResponse().getClickedButtonId();
            showDetailForm(player, emails.get(buttonId));
        }));
        player.showFormWindow(form);
    }

    // 详情界面表单
    public static void showDetailForm(Player player, EmailData email) {
        FormWindowSimple form = new FormWindowSimple("邮件详情", buildDetailContent(email));
        form.addButton(new ElementButton("§l§a确认"));
        form.addButton(new ElementButton("§l§c返回"));
        if (email.getFlag() < 2 && !email.getItems().isEmpty()) {
            form.addButton(new ElementButton("§l§e领取附件"));
        }
        if(email.getFlag() == 0) email.setFlag(1);
        form.addHandler(FormResponseHandler.withoutPlayer(ignored -> {
            if (form.wasClosed()) return;
            // 获取点击的按钮索引
            int buttonId = form.getResponse().getClickedButtonId();
            switch (buttonId) {
                case 0 -> {
                }
                case 1 -> showMainForm(player, manager.getPlayerEmails(player.getName()));
                case 2 -> {
                    for(Item item : email.getItems()) {
                        Tool.addItem(player, item);
                        player.sendMessage("§a成功领取所有附件！");
                    }
                    email.setFlag(2);
                    showMainForm(player, manager.getPlayerEmails(player.getName()));
                }
            }
        }));
        player.showFormWindow(form);
    }

    private static String formatTime(long timestamp) {
        return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm")
                .format(new java.util.Date(timestamp * 1000));
    }

    private static String getStatusText(int flag) {
        return switch (flag) {
            case 0 -> "§l§6未读";
            case 1 -> "§l§a已读";
            case 2 -> "§l§c已领取";
            default -> "";
        };
    }

    private static String buildDetailContent(EmailData email) {
        return String.format(
                "§l§e来自%s §r§7%s\n" +
                        "§l§e剩余天数: §r§7%d天\n" +
                        "§l§e状态: §r%s\n" +
                        "§l§e内容: §r§f%s\n" +
                        "§l§e附件: §r§7%s",
                email.getFrom(),
                formatTime(email.getTimestamp()),
                calculateRemainDays(email),
                getStatusText(email.getFlag()),
                email.getText(),
                formatItems(email.getItems())
        );
    }

    private static int calculateRemainDays(EmailData email) {
        long expireTime = email.getTimestamp() + email.getKeepDays() * 86400L;
        return (int) ((expireTime - System.currentTimeMillis()/1000) / 86400);
    }

    private static String formatItems(List<Item> items) {
        if (items.isEmpty()) return "无";
        return items.stream()
                .map(item -> item.getName() + "×" + item.getCount())
                .collect(java.util.stream.Collectors.joining(", "));
    }
}
